import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login.vue'
import Register from '@/views/register.vue'
import Detail from '@/views/detail.vue'
import Layout from '@/views/layout.vue'
// 二级路由
import Article from '@/views/article.vue'
import Collect from '@/views/collect.vue'
import Like from '@/views/like.vue'
import User from '@/views/user.vue'
import { getToken } from '@/utils/storage'

Vue.use(VueRouter)

const routes = [
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/detail', component: Detail },
  {
    path: '/',
    component: Layout,
    redirect: 'article',
    children: [
      { path: 'article', component: Article },
      { path: 'collect', component: Collect },
      { path: 'like', component: Like },
      { path: 'user', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})

// befor 在...之前  Each 每个人
// to 去哪 ---- from 从哪来 ---- next 下一个

// 跳转之前先到这里
// 白名单
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
  const token = getToken()

  if (whiteList.includes(to.path)) { // 如果在白名单中
    next() // 放行
  } else if (token) { // 不在 手里有token
    next() // 放行
  } else {
    next('/login')// 否则 强制转登录
  }
})
export default router
